import { ref } from "vue";
import { ElLoading } from "element-plus";
import { emitter } from "@/utils/emitter";
import { loadingSvg } from "./common";


//定义实例
const instance = ref<any>(null);
//打开loading
const open = (target: string | null = null, text: string = "数据加载中..."): void => {
    instance.value = ElLoading.service({
        target: target ? target : "document.body",
        fullscreen: true,
        lock: true,
        text: text,
        background: "rgba(0, 0, 0, 0)",
        svg: loadingSvg,
        svgViewBox: "-10, -10, 50, 50",
    });
};

//关闭loading
const close = (): void => instance?.value?.close();

/**
 * 事件总线
 * @param target 事件目标
 * @param text 提示信息
 */
emitter.on("loading-open", payload => {
    if (typeof payload === "string") {
        open(payload);
    } else if (typeof payload === "object") {
        open(payload.target, payload.text);
    } else {
        open();
    }
});
emitter.on("loading-close", () => close());

export { open, close };
